package Server;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.Socket;
import java.util.Random;
import java.util.Scanner;

import Application.WorkUnit;
import Application.WorkUnitImplementation;
import Networking.INetworkServer;
import Networking.NetworkHandler;

public class ClientHandler implements INetworkServer {

	private static Random rand = new Random();

	private MainServer mainServer;
	private int clientID;
	private WorkUnit lastSentWorkUnit;
	private NetworkHandler networkHandler;
	private boolean isAlive = true;
	private ClientDispatcher parent;

	private static int nextUnitID = 1;

	public ClientHandler(Socket socket, ClientDispatcher parent) {
//		mainServer = mainS;
		networkHandler = new NetworkHandler(socket, this);
		this.parent = parent;
	}

	public void sendUnit(String message) {
		// int unitId = rand.nextInt();
		int unitId = nextUnitID++;
		System.out.println("Sending Unit# " + unitId + " to Client: "
				+ clientID);
		lastSentWorkUnit = new WorkUnitImplementation(unitId, clientID);
		networkHandler.sendNewWorkUnit(lastSentWorkUnit);
	}
	
	public void sendUnit(WorkUnit unit) {
		lastSentWorkUnit = unit;
		networkHandler.sendNewWorkUnit(unit);
	}

	public WorkUnit getLastSentWorkUnit() {
		return lastSentWorkUnit;
	}

	public int getClientID() {
		return clientID;
	}

	public boolean isAlive() {
		return isAlive;
	}

	@Override
	public void gotNewClient(int clientID) {
		this.clientID = parent.gotNewClient(clientID, this);
		networkHandler.sendNewClientConfirm(this.clientID);
	}

	@Override
	public void clientDisconnected(int clientID) {
//		mainServer.clientDisconnected(this);
		isAlive = false;
	}

	@Override
	public void finishedWorkUnit(WorkUnit workUnit) {
		parent.finishedWorkUnit(workUnit, this);
		
	}
}
